package com.it.schoolbookshop_back.controller.admin;

import com.it.schoolbookshop_back.entities.dto.CreateUserDTO;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.entities.vo.user.UserResetPwd;
import com.it.schoolbookshop_back.entities.vo.user.UserStatistics;
import com.it.schoolbookshop_back.entities.vo.user.UserUpdateRole;
import com.it.schoolbookshop_back.entities.vo.user.UserUpdateStatus;
import com.it.schoolbookshop_back.enums.UserRoleEnums;
import com.it.schoolbookshop_back.enums.UserStatusEnums;
import com.it.schoolbookshop_back.service.AdminUserManageService;
import com.it.schoolbookshop_back.service.BookService;
import com.it.schoolbookshop_back.service.UserService;
import com.it.schoolbookshop_back.utils.PageBean;
import com.it.schoolbookshop_back.utils.UserContext;
import com.it.schoolbookshop_back.utils.UserValidationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/api/admin")
public class AdminUserManageController {
    @Autowired
    private AdminUserManageService adminService;

    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    /**
     * 管理员获取用户信息
     * @param page 页码，默认1
     * @param limit 每页数量，默认10
     * @param query 搜索关键词（查询用户名、真实姓名、学号）
     * @param status 筛选状态('active', 'suspended', 'deleted')
     * @param role 筛选角色('student', 'admin')
     * @param sortBy 排序字段('created_at', 'username', 'login_at')
     * @return
     */
    @GetMapping("/users")
    public Result<PageBean<User>> getUserInform(@RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer limit,
                                String query,String status,String role,String sortBy){

        PageBean<User> pageBean = adminService.getUserInform(page,limit,query,status,role,sortBy);

        return Result.success("获取用户列表成功",pageBean);
    }

    /**
     * 管理员获取用户详情
     * @param id
     * @return
     */
    @GetMapping("/users/{id}")
    public Result<User> getUserDetail(@PathVariable int id){
        User user = adminService.getUserDetail(id);
        return Result.success("获取用户详情成功",user);
    }

    /**
     * 修改用户状态 (使用数字代码)
     * @param id 用户ID
     * @param statusCode 状态代码 (0:ACTIVE, 1:SUSPENDED, 2:DELETED)
     * @return
     */
    @PutMapping("/users/{id}/status/{statusCode}")
    public Result<UserUpdateStatus> updateUserStatusByCode(@PathVariable int id, @PathVariable int statusCode){
        UserStatusEnums statusEnum = UserStatusEnums.getByCode(statusCode);
        if (statusEnum == null) {
            return Result.failed("无效的状态代码");
        }
        
        UserUpdateStatus statusResult = adminService.updateUserStatus(id, statusEnum.name());
        return Result.success("用户状态更新成功", statusResult);
    }
    
    /**
     * 修改用户状态 (使用字符串)
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/users/{id}/status/string/{status}")
    public Result<UserUpdateStatus> updateUserStatus(@PathVariable int id, @PathVariable String status){
        UserUpdateStatus statusResult = adminService.updateUserStatus(id, status);
        return Result.success("用户状态更新成功", statusResult);
    }

    /**
     * 重置用户密码
     * @param id
     * @param resetPassword
     * @return
     */
    @PostMapping("/users/{id}/{resetPassword}")
    public Result<UserResetPwd> resetUserPassword(@PathVariable int id, @PathVariable String resetPassword){
        UserResetPwd pwdResult = adminService.resetUserPassword(id, resetPassword);
        return Result.success("密码重置成功", pwdResult);
    }

    /**
     * 修改用户角色 (使用数字代码)
     * @param id 用户ID
     * @param roleCode 角色代码 (0:STUDENT, 1:ADMIN)
     * @return
     */
    @PutMapping("/users/{id}/role/{roleCode}")
    public Result<UserUpdateRole> updateUserRoleByCode(@PathVariable int id, @PathVariable int roleCode){
        UserRoleEnums roleEnum = UserRoleEnums.getByCode(roleCode);
        if (roleEnum == null) {
            return Result.failed("无效的角色代码");
        }
        
        UserUpdateRole roleResult = adminService.updateUserRole(id, roleEnum.name());
        return Result.success("用户角色更新成功", roleResult);
    }

    /**
     * 修改用户角色 (使用字符串)
     * @param id
     * @param role
     * @return
     */
    @PutMapping("/users/{id}/role/string/{role}")
    public Result<UserUpdateRole> updateUserRole(@PathVariable int id, @PathVariable String role){
        if (role == null) {
            return Result.failed("缺少角色role");
        }
        UserUpdateRole roleResult = adminService.updateUserRole(id, role);
        return Result.success("用户角色更新成功", roleResult);
    }

    /**
     * 获取用户统计数据
     * @return
     */
    @GetMapping("/statistics/users")
    public Result<UserStatistics> getUserStatistics(){
        UserStatistics statistics = adminService.getUserStatistics();
        return Result.success("用户统计数据成功", statistics);
    }

    /**
     * 管理员新增用户
     * @param createUserDTO 包含用户名和角色的DTO
     * @return 创建结果
     */
    @PostMapping("/users")
    public Result<Map<String, Object>> createUser(@RequestBody CreateUserDTO createUserDTO) {
        log.info("管理员创建新用户: {}", createUserDTO.getUsername());
        
        // 验证参数
        Result<?> validationResult = UserValidationUtils.validateCreateUser(createUserDTO, userService);
        if (validationResult != null) {
            return (Result<Map<String, Object>>) validationResult;
        }
        
        // 创建用户对象
        User user = UserValidationUtils.createUserFromDTO(createUserDTO);
        
        // 确保设置正确的角色
        if (createUserDTO.getRole() != null) {
            user.setRole(createUserDTO.getRole());
        } else {
            // 如果没有指定角色，默认为学生
            user.setRole(UserRoleEnums.STUDENT.name());
        }
        
        // 调用服务层创建用户
        Integer userId = userService.register(user);
        
        if (userId == null) {
            return Result.failed("创建用户失败");
        }
        
        // 获取创建后的用户信息
        User createdUser = userService.getUserById(userId);
        
        // 构建简化的返回结果
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("id", createdUser.getId());
        responseData.put("username", createdUser.getUsername());
        responseData.put("password", createdUser.getPassword());
        responseData.put("role", createdUser.getRole());
        
        return Result.success("用户创建成功", responseData);
    }

    /**
     * 管理员删除用户
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/users/{id}")
    public Result<Map<String, Object>> deleteUser(@PathVariable int id) {
        log.info("管理员删除用户, ID: {}", id);
        
        // 获取当前管理员ID
        Integer adminId = UserContext.getUserId();
        if (adminId == null) {
            return Result.unauthorized();
        }
        
        // 不能删除自己
        if (adminId == id) {
            log.warn("管理员尝试删除自己的账号, ID: {}", id);
            return Result.failed("管理员不能删除自己的账号");
        }
        
        // 查询被删除的用户信息
        User userToDelete = userService.getUserById(id);
        
        // 用户不存在
        if (userToDelete == null) {
            return Result.failed("用户不存在");
        }
        
        // 查询当前管理员信息
        User adminUser = userService.getUserById(adminId);
        
        // 不能删除相同级别的用户（管理员不能删除管理员）
        if ("admin".equalsIgnoreCase(userToDelete.getRole()) && 
            "admin".equalsIgnoreCase(adminUser.getRole())) {
            log.warn("管理员尝试删除同级别用户, 管理员ID: {}, 目标用户ID: {}", adminId, id);
            return Result.failed("管理员不能删除同级别的用户");
        }
        
        // 保存删除前的用户信息用于返回
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("id", userToDelete.getId());
        responseData.put("username", userToDelete.getUsername());
        responseData.put("password", userToDelete.getPassword());
        responseData.put("role", userToDelete.getRole());
        
        // 删除用户发布的所有书籍
        boolean booksDeleted = adminService.deleteUserBooks(id);
        if (!booksDeleted) {
            log.warn("删除用户{}的书籍失败", id);
            // 即使书籍删除失败，也继续尝试删除用户
        } else {
            log.info("成功删除用户{}的所有书籍", id);
        }
        
        // 执行删除用户操作
        boolean success = adminService.deleteUser(id);
        
        if (!success) {
            return Result.failed("删除用户失败");
        }
        
        log.info("成功删除用户: ID={}, 用户名={}, 角色={}", id, userToDelete.getUsername(), userToDelete.getRole());
        return Result.success("删除用户成功", responseData);
    }
}
